package net.sivak.proc.recursion.parser;

/**
 * Created with IntelliJ IDEA.
 * User: root
 * Date: 1/22/13
 * Time: 12:53 PM
 * To change this template use File | Settings | File Templates.
 */
public class Parser {
    public static void main(String[] args) {
        System.out.println(eval("123"));
        System.out.println(eval("2*3"));
        System.out.println(eval("2*(1+3)"));
        System.out.println(eval("(2+3)+2"));
        System.out.println(eval("1+(5-2*(13/6))"));
    }

    private static int eval(String expr) {
        return eval(expr, 0, expr.length());
    }

    private static int eval(String expr, int from, int to) {
            int pos = from;
            while (pos < to) {
                if (Character.isDigit(expr.charAt(pos))) {
                    pos++;
                } else {
                    int leftOperand = 0;
                    if (expr.charAt(pos) == '(' && pos == 0) {
                        leftOperand = eval(expr, pos + 1, expr.indexOf(")", pos + 1));
                        pos = expr.indexOf(")", pos + 1) + 1;
                    } else leftOperand = Integer.valueOf(expr.substring(from, pos));
                    char operation = expr.charAt(pos);
                    int rightOperand = 0;
                    if (expr.charAt(pos + 1) == '(')
                        rightOperand = eval(expr, pos + 2, to - 1);
                    else rightOperand = eval(expr, pos + 1, to);
                    switch (operation) {
                        case '+':
                            return leftOperand + rightOperand;
                        case '-':
                            return leftOperand - rightOperand;
                        case '*':
                            return leftOperand * rightOperand;
                        case '/':
                            return leftOperand / rightOperand;
                    }
                }
            }
            return Integer.valueOf(expr.substring(from, to));
    }
}
